/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.datalogging.web.controller;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.api.context.Context;
import org.openmrs.module.datalogging.configuration.Variable;
import org.openmrs.module.datalogging.enums.OffsetType;
import org.openmrs.module.datalogging.enums.ValueType;
import org.openmrs.module.datalogging.enums.VariableType;
import org.openmrs.module.datalogging.filter.Filter;
import org.openmrs.module.datalogging.filter.FilterFactory;
import org.openmrs.module.datalogging.filter.FilterUtils;
import org.openmrs.module.datalogging.handler.variable.VariableHandler;
import org.openmrs.module.datalogging.handler.variable.VariableHandlerFactory;
import org.openmrs.module.datalogging.service.DataLoggingService;
import org.openmrs.module.datalogging.web.model.VariableModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 *
 */
@Controller
@RequestMapping("/module/datalogging/variableForm")
public class VariableFormController {
	
	private static final Log log = LogFactory.getLog(VariableFormController.class);
	
	@RequestMapping(method = RequestMethod.GET)
	public void preparePage(@RequestParam(required = false, value = "variableId") Integer id, ModelMap map) {
		if (Context.isAuthenticated()) {
			DataLoggingService service = Context.getService(DataLoggingService.class);
			
			VariableModel variableModel = new VariableModel();
			if (id != null) {
				try {
					Variable variable = service.getComponent(id);
					BeanUtils.copyProperties(variableModel, variable);
					
					VariableHandler variableHandler = VariableHandlerFactory.getHandler(variable.getVariableType());
					String[] filterExpressions = StringUtils.split(variable.getFilterExpression(), FilterUtils.EXPRESSION_SEPARATOR);
					for (String filterExpression : filterExpressions) {
						String filterKey = filterExpression .substring(0, filterExpression.indexOf(FilterUtils.KEY_SEPARATOR));
						if (variableHandler.supportFilter(filterKey)) {
							String filterValue = filterExpression.substring(filterExpression.indexOf(FilterUtils.KEY_SEPARATOR) + 1);
							BeanUtils.setProperty(variableModel, filterKey, filterValue);
							
							Filter filterHandler = FilterFactory.getHandler(filterKey);
							Set<Object> objects = new HashSet<Object>();
							String[] filterValues = StringUtils.split(filterValue, FilterUtils.VALUE_SEPARATOR);
							for (String value : filterValues) {
								Object object = filterHandler.getFilterValue(value);
								if (object != null)
									objects.add(object);
							}
							map.addAttribute(filterKey, objects);
						}
					}
				} catch (Exception e) {
					log.error("Error creating command object for the controller ...", e);
				}
			}
			
			map.addAttribute("variable", variableModel);
			map.addAttribute("types", VariableType.values());
			map.addAttribute("offsets", OffsetType.values());
			map.addAttribute("values", ValueType.values());
		}
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String process(@ModelAttribute("variable") VariableModel variableModel) throws Exception {
		if (Context.isAuthenticated()) {
			DataLoggingService service = Context.getService(DataLoggingService.class);
			
			Variable variable = new Variable();
			if (variableModel.getVariableId() != null)
				variable = service.getComponent(variableModel.getVariableId());
			
			BeanUtils.copyProperties(variable, variableModel);
			
			Set<String> filterExpression = new HashSet<String>();
			VariableHandler variableHandler = VariableHandlerFactory.getHandler(variable.getVariableType());
			for (String supportedFilter : variableHandler.getSupportedFilters()) {
				String filterValue = BeanUtils.getProperty(variableModel, supportedFilter);
				if (StringUtils.isNotBlank(filterValue))
					filterExpression.add(StringUtils.join(Arrays.asList(supportedFilter, filterValue), FilterUtils.KEY_SEPARATOR));
			}
			variable.setFilterExpression(StringUtils.join(filterExpression, FilterUtils.EXPRESSION_SEPARATOR));
			
			service.saveComponent(variable);
		}
		return "redirect:variableList.list";
	}
	
}
